/*
 */
package org.hook.showcase.concurrent.tools;

import java.util.concurrent.CountDownLatch;

/**
 * @author suwuqiang 2011-12-16
 */
public class CountDownLatchCase {

	public long timecost(final int times, final Runnable task) throws InterruptedException {
		if (times <= 0)
			throw new IllegalArgumentException();
		final CountDownLatch startLatch = new CountDownLatch(1);
		final CountDownLatch overLatch = new CountDownLatch(times);
		for (int i = 0; i < times; i++) {
			new Thread(new Runnable() {
				public void run() {
					try {
						startLatch.await(); // 线程等待计数器为0后执行任务
						task.run();
					} catch (InterruptedException ex) {
						Thread.currentThread().interrupt();
					} finally {
						overLatch.countDown(); // 标记任务完成(任务数减一)
					}
				}
			}).start();
		}
		long start = System.nanoTime();
		startLatch.countDown(); // 任务线程同时执行
		overLatch.await(); // 主线程等待至任务线程都执行完成(计数器为0)
		return System.nanoTime() - start;
	}

	private static class doNothingTask extends Thread {

		@Override
		public void run() {
			try {
				System.out.println("Current Task:[" + this.getName() + this.getId() + "] executing...");
				sleep(5);
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
		}
	}

	public static void main(String[] args) {
		final CountDownLatchCase tool = new CountDownLatchCase();
		final doNothingTask task = new doNothingTask();
		try {
			long timecost = tool.timecost(10000, task);
			System.out.println("TimeCost:" + timecost + "(ms)");
		} catch (InterruptedException e) {
			e.printStackTrace();
		}
	}
}